const {think} = require('thinkjs');
const assert = require('assert');
const aunVerificationRouter = require('../config/unVerificationRouter');
const Redis = require('think-redis');
const config = require('../config/config');
let redisInst = new Redis(config.redis);
module.exports = class extends think.Controller {
  static get _REST() {
    return true;
  }

  constructor(ctx:any) {
    super(ctx);

    this.ctx = ctx;
    assert(think.isFunction(this.model), 'this.model must be a function');
    this.modelInstance = this.model(this.resource);
  }

  async __before() {
    let token = await redisInst.get('ayybyy-' + 'token');
    if (token === undefined && !aunVerificationRouter[this.ctx.req._parsedUrl.pathname]) {
      think.logger.debug(this.ctx.req._parsedUrl.pathname);
      return this.fail(403, `登陆已过期，请重新登陆!${this.ctx.req._parsedUrl.pathname}`);
    }
  }

  /**
   * put resource
   * @return {Promise} []
   */
  async postAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    delete data[pk];
    if (think.isEmpty(data)) {
      return this.fail('data is empty');
    }
    const insertId = await this.modelInstance.add(data);
    return this.success({id: insertId});
  }

  /**
   * delete resource
   * @return {Promise} []
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail('params error');
    }
    const pk = this.modelInstance.pk;
    const rows = await this.modelInstance.where({[pk]: this.id}).delete();
    return this.success({affectedRows: rows});
  }

  /**
   * update resource
   * @return {Promise} []
   */
  async putAction() {
    if (!this.id) {
      return this.fail('params error');
    }
    const pk = this.modelInstance.pk;
    const data = this.post();
    data[pk] = this.id; // rewrite data[pk] forbidden data[pk] !== this.id
    if (think.isEmpty(data)) {
      return this.fail('data is empty');
    }
    const rows = await this.modelInstance.where({[pk]: this.id}).update(data);
    return this.success({affectedRows: rows});
  }

  __call() {
  }
};
